package cn.cyj.security.sms;

import cn.cyj.security.security.UserDetailService;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 提供短信验证码登录的支持
 */

@Data
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private UserDetailService userDetailService;

    /**
     * 调用userDetailService来查询登录用户是否存在,在验证短信验证码过滤器之后,校验登录用户是否存在
     * 执行流程:
     * 获取用户登录信息
     * 查询用户是否存在
     * 将登录用户信息转存带自定义的用户信息类
     * 返回
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
        UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());

        if (userDetails == null)
            throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");

        SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * 指定谁来处理登录用户的token类型
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return SmsAuthenticationToken.class.isAssignableFrom(aClass);
    }

}
